﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Menu;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Menu
{
    public class UpdateMenuCommonHandle:IRequestHandler<UpdateMenuCommon,ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> MenuDal;
        private readonly IMapper mapper;
        public UpdateMenuCommonHandle(IBaseRepository<MenuModel> menuDal, IMapper mapper)
        {
            MenuDal = menuDal;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateMenuCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var info = MenuDal.GetAll().Where(x => x.MenuName == request.MenuName && x.IsDeleted == false && x.ParentId == request.ParentId && x.MenuId != request.MenuId).FirstOrDefault();

            if (info != null)
            {
                res.Code = ApiEnum.Error;
                res.Message = "同一级别种菜单名称不允许重复";
                return Task.FromResult(res);
            }

            var infos = MenuDal.GetValue(request.MenuId).Result;


            var model = mapper.Map(request, infos);
            model.UpdateBy = "admin";
            model.UpdateDate = DateTime.Now;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = MenuDal.Update(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "修改成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "修改失败";
                return Task.FromResult(res);
            }
        }


    }
}
